package com.hopu.v1.service.front.exam.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopu.v1.exception.BusinessException;
import com.hopu.v1.mapper.front.exam.EGradesMapper;
import com.hopu.v1.mapper.front.exam.ExamMapper;
import com.hopu.v1.pojo.exam.*;
import com.hopu.v1.pojo.question.ErrorNotebookOptions;
import com.hopu.v1.pojo.question.ErrorNotebooksQuestions;
import com.hopu.v1.service.front.exam.EGradesService;
import com.hopu.v1.service.front.exam.EStudentRecordsService;
import com.hopu.v1.service.front.exam.ExamService;
import com.hopu.v1.service.front.question.FErrorNotebooksQuestionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
* @author lihao
* @description 针对表【t_exam_grades(考试成绩表)】的数据库操作Service实现
* @createDate 2024-09-29 15:31:04
*/
@Service
public class EGradesServiceImpl extends ServiceImpl<EGradesMapper, ExamGrades>
    implements EGradesService {
    @Autowired
    private EGradesMapper examGradesMapper;
    @Autowired
    private ExamMapper examRecordsMapper;
    @Autowired
    private ExamService examService;
    @Autowired
    private EStudentRecordsService studentRecordsService;


    @Autowired
    private FErrorNotebooksQuestionsService fErrorNotebooksQuestionsService;

    /**
     * 查询列表
     * @param page
     * @param examGrades
     * @param endTime
     * @return
     */
    @Override
    public IPage<ExamGrades> selectList(Page<ExamGrades> page, ExamGrades examGrades, String endTime) {
        LambdaQueryWrapper<ExamGrades> wrapper = new LambdaQueryWrapper<>();
        if (examGrades.getCreateTime() != null) {
            wrapper.between(ExamGrades::getCreateTime, examGrades.getCreateTime(),endTime);
        }
        wrapper.orderByDesc(ExamGrades::getCreateTime);
        return examGradesMapper.selectPage(page, wrapper);
    }

    @Transactional
    @Override
    public void batchDel(ArrayList<Integer> ids) {
        if (ids.isEmpty()){
            throw new BusinessException("ids不能为空");
        }else{
            examGradesMapper.deleteByIds(ids);
        }
    }

    /**
     * 用户提交考卷
     * 写入答案表、修改学生该试卷状态
     * @param examGradesList
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ExamStudentRecords batchAdd(String studentId,List<ExamGrades> examGradesList) {
        // 设置创建时间
        LocalDateTime now = LocalDateTime.now();
        examGradesList.forEach(examGrades -> examGrades.setCreateTime(now));

        // 成绩
        double[] score = {0};

        // 获取试卷
        ExamRecords records = getExamRecords(examGradesList);
        if (records == null) {
            throw new BusinessException("未查到该试卷");
        }

        ExamRecords exam = examService.getStudentOneExam(records.getId(), studentId);
        boolean hasSubjectiveQuestion = exam.getList().stream()
                .anyMatch(q -> q.getQuestionType().equals("3"));

        // 处理题目
//        if (!hasSubjectiveQuestion) {
            List<ErrorNotebooksQuestions> errorNotebooksQuestionsList = new ArrayList<>();
            processExamQuestions(studentId,exam, examGradesList, score, errorNotebooksQuestionsList);
            System.out.println("errorNotebooksQuestionsList"+errorNotebooksQuestionsList);
            fErrorNotebooksQuestionsService.addErrorExam(errorNotebooksQuestionsList);
//        }

        // 插入答案表记录
        examGradesMapper.insert(examGradesList);
        updateExamRecordStatus(examGradesList);

        // 创建学生考试记录
        return createExamStudentRecords(studentId,examGradesList, now, records, score[0], hasSubjectiveQuestion);
    }

    private ExamRecords getExamRecords(List<ExamGrades> examGradesList) {
        LambdaQueryWrapper<ExamRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExamRecords::getId, examGradesList.get(0).getExamRecordId());
        return examRecordsMapper.selectOne(queryWrapper);
    }

    private void processExamQuestions(String studentId,ExamRecords exam, List<ExamGrades> examGradesList, double[] score,
                                      List<ErrorNotebooksQuestions> errorNotebooksQuestionsList) {
        for (int i = 0; i < exam.getList().size(); i++) {
            ExamQuestions item = exam.getList().get(i);

            if (isMultipleChoice(item)) {
                String gradesString = getCorrectAnswerString(item);
                boolean isCorrect = processStudentAnswers(examGradesList, item, gradesString, score);

                int count = -1;
                if (!isCorrect) {
                    count++;
                    ErrorNotebooksQuestions errorNotebooksQuestions = createErrorNotebook(studentId,exam, item, examGradesList,count);
                    System.out.println("item" + item);
//                    System.out.println(errorNotebooksQuestions.getOptions().get(i));
//                    System.out.println(examGradesList.get(i).getStudentOption());
//                    errorNotebooksQuestions.getOptions().get(i).setOptions(examGradesList.get(i).getStudentOption());
//                    errorNotebooksQuestions.getOptions().get(i).setOptions(examGradesList.get(i).getStudentOption());
                    errorNotebooksQuestionsList.add(errorNotebooksQuestions);
                }
                System.out.println(errorNotebooksQuestionsList.size());
                System.out.println(errorNotebooksQuestionsList);
                System.out.println(count);
                if(errorNotebooksQuestionsList.size()>0&&count>=0){
                    errorNotebooksQuestionsList.get(count).setStudentAnswer(examGradesList.get(i).getStudentOption());

                }
            }
        }

    }

    private boolean isMultipleChoice(ExamQuestions item) {
        return item.getQuestionType().equals("0") || item.getQuestionType().equals("1") || item.getQuestionType().equals("2");
    }

    private String getCorrectAnswerString(ExamQuestions item) {
        return item.getOptions().stream()
                .filter(option -> "1".equals(String.valueOf(option.getIsCorrect())))
                .map(option -> String.valueOf(option.getId()))
                .collect(Collectors.joining(","));
    }

    private boolean processStudentAnswers(List<ExamGrades> examGradesList, ExamQuestions item, String gradesString, double[] score) {
        for (ExamGrades examGrades : examGradesList) {
            if (examGrades.getQuestionId().equals(item.getId()) && gradesString.equals(examGrades.getStudentAnswer())) {
                score[0] += examGrades.getScore();
                System.out.println("正确");
                return true; // 答案正确
            }
        }
        return false; // 答案错误
    }

    private ErrorNotebooksQuestions createErrorNotebook(String studentId,ExamRecords exam, ExamQuestions item, List<ExamGrades> examGradesList,int index) {
        ErrorNotebooksQuestions errorNotebooksQuestions = new ErrorNotebooksQuestions();
        errorNotebooksQuestions.setErrorQuestion(item.getQuestionTitle());
        errorNotebooksQuestions.setStudentId(studentId);
        errorNotebooksQuestions.setErrorSource(exam.getExamType() == 1 ? 1 : 2); // 错误来源
        errorNotebooksQuestions.setQuestionType(item.getQuestionType());
        errorNotebooksQuestions.setStatus(0);

        String[] optionsArray = {"A", "B", "C", "D"};
        AtomicInteger i = new AtomicInteger(0);

        List<ErrorNotebookOptions> errorNotebookOptionsList = item.getOptions().stream()
                .map(option -> {
                    ErrorNotebookOptions errorNotebookOptions = new ErrorNotebookOptions();
                    // 根据索引设置选项
                    String currentOption = optionsArray[i.getAndIncrement()];
                    errorNotebookOptions.setOptions(currentOption);

                    errorNotebookOptions.setOptionDescribe(option.getOptionText());
                    errorNotebookOptions.setStatus(String.valueOf(option.getIsCorrect()));
                    errorNotebookOptions.setErrorNotebookId(errorNotebooksQuestions.getId());
                    return errorNotebookOptions;
                })
                .collect(Collectors.toList());

        errorNotebooksQuestions.setOptions(errorNotebookOptionsList);
        return errorNotebooksQuestions;
    }

//    private String getOptionLabel(ExamOptionAnswer option) {
//        String[] optionsArray = {"A", "B", "C", "D"};
//        System.out.println(option);
//        return optionsArray[Integer.parseInt(String.valueOf(option.getId()))];
//    }
        private String getOptionLabel(ExamOptionAnswer option, List<ExamOptionAnswer> options) {
            String[] optionsArray = {"A", "B", "C", "D"};
            System.out.println("option选项"+option);
            System.out.println("list"+options);
            // 根据该题目的选项在当前题目中的顺序进行映射
            int index = options.indexOf(option); // 找到当前选项在列表中的位置

            System.out.println("选项"+optionsArray[index]);
            // 检查索引是否有效
            if (index >= 0 && index < optionsArray.length) {
                return optionsArray[index];
            } else {
                throw new IllegalArgumentException("无法匹配选项标签，索引无效");
            }
        }

    private void updateExamRecordStatus(List<ExamGrades> examGradesList) {
        ExamRecords examRecords = examRecordsMapper.selectById(examGradesList.get(0).getExamRecordId());
        examRecords.setQuestionExamStatus(1);
//        examRecords.setStatus(2);
        examRecordsMapper.updateById(examRecords);
    }

    private ExamStudentRecords createExamStudentRecords(String studentId,List<ExamGrades> examGradesList, LocalDateTime now,
                                                        ExamRecords records, double totalScore, boolean hasSubjectiveQuestion) {
        ExamStudentRecords examStudentRecords = new ExamStudentRecords();
        examStudentRecords.setExamRecordId(records.getId());
        examStudentRecords.setStudentId(studentId);
        examStudentRecords.setCreateTime(now);
        examStudentRecords.setCreateBy(examGradesList.get(0).getCreateBy());
        examStudentRecords.setScore(BigDecimal.valueOf(totalScore));
        examStudentRecords.setExamStatus(hasSubjectiveQuestion ? 2 : 3);
        studentRecordsService.save(examStudentRecords);
        return examStudentRecords;
    }

}




